package com.mocne.MocneAutoTest;

import com.mocne.Common.Excel2Dataprovider;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static org.testng.Assert.fail;

public class UITestTestNG_TestCase {
    private WebDriver driver;
    private boolean acceptNextAlert = true;
    private StringBuffer verificationErrors = new StringBuffer();
    private static Jedis jedis = new Jedis("localhost");

    @DataProvider(name = "testData")
    public static Object[][] testData() {

        Object[][] dataProvider = new Object[][]{};

        try {
            String dpFile = jedis.get("dpFile");
            String dpPath = jedis.get("dpPathPath");
            if (!dpFile.equals("") && !dpPath.equals("")) {
                Excel2Dataprovider e = new Excel2Dataprovider(dpPath + dpFile, "cases");
                dataProvider = e.getExcelData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataProvider;
    }

    @BeforeClass(alwaysRun = true)
    public void setUp() {
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test(dataProvider = "testData")
    public void testUITestCase(HashMap<String, String> data) {
        System.out.println(data.toString());
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    private boolean isAlertPresent() {
        try {
            driver.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    private String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }
}
